package com.example.osixaffairssystem.controller;

import com.example.osixaffairssystem.domain.PageBean;
import com.example.osixaffairssystem.domain.Result;
import com.example.osixaffairssystem.domain.model.Class;
import com.example.osixaffairssystem.domain.model.Course;
import com.example.osixaffairssystem.service.CourseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/course")
@RequiredArgsConstructor
public class CourseController {

    final CourseService courseService;

    @GetMapping("/list")
    public Result list() {
        log.info("获取课程信息");
        List<Course> list = courseService.list();
        return Result.success(list);
    }

    @GetMapping
    public Result listToPage(@RequestParam() Integer page, @RequestParam() Integer pageSize) {
        log.info("分页查询课程{ page: {}, pageSize: {} }", page, pageSize);
        PageBean<Course> list = courseService.listToPage(page, pageSize);
        return Result.success(list);
    }

    @PostMapping
    public Result insert(@RequestBody Course course) {
        log.info("新增课程{}", course);
        Integer id = null;
        try {
            id = courseService.insert(course);
        } catch (DuplicateKeyException e) {
            return new Result(HttpStatus.CONFLICT.value(), "Duplicate_Key", null);
        }
        return Result.success(id);
    }

    @PutMapping
    public Result update(@RequestBody Course course) {
        log.info("修改课程{}", course);
        courseService.update(course);
        return Result.success();
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids) {
        log.info("删除课程{}", ids);
        courseService.delete(ids);
        return Result.success();
    }
}
